package estore.view;

import estore.model.Product3;
import estore.service.ProductService3;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class ConsoleShop3 {

    private final ProductService3 productService = new ProductService3();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        System.out.println("🎉 欢迎来到电子商城！");

        while (true) {
            showMenu();
            int choice = getIntInput("请输入您的选择: ");
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    searchProductsByTag();
                    break;
                case 3:
                    viewAllTags();
                    break;
                case 4:
                    addToCart();
                    break;
                case 5:
                    viewCart();
                    break;
                case 6:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效的选项，请重新输入！");
            }

            // 按回车继续
            if (choice != 6) {
                System.out.print("\n按回车键继续...");
                scanner.nextLine();
            }
        }
    }

    private void showMenu() {
        System.out.println("\n" + "=".repeat(60));
        System.out.println("🏪 电子商城管理系统");
        System.out.println("=".repeat(60));
        System.out.println("1. 📋 浏览所有商品");
        System.out.println("2. 🔍 按标签搜索商品");
        System.out.println("3. 🏷️  查看所有标签");
        System.out.println("4. 🛒 添加商品到购物车");
        System.out.println("5. 🛍️  查看购物车");
        System.out.println("6. 🚪 退出系统");
        System.out.println("-".repeat(60));
    }

    private void browseProducts() {
        System.out.println("\n--- 所有商品列表 ---");
        List<Product3> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            System.out.println("商品总数: " + products.size());
            System.out.println("-".repeat(80));
            for (Product3 product : products) {
                System.out.println(product);
            }
            System.out.println("-".repeat(80));

            // 显示标签统计
            displayTagStatistics();
        }
    }

    private void searchProductsByTag() {
        Set<String> allTags = productService.getAllTags();
        if (allTags.isEmpty()) {
            System.out.println("当前没有可用的标签。");
            return;
        }

        System.out.println("\n--- 按标签搜索商品 ---");
        System.out.println("可用标签: " + allTags);
        System.out.print("请输入要搜索的标签: ");
        String tag = scanner.nextLine().trim();

        if (tag.isEmpty()) {
            System.out.println("标签不能为空！");
            return;
        }

        List<Product3> results = productService.findProductsByTag(tag);
        if (results.isEmpty()) {
            System.out.println("没有找到包含标签 '" + tag + "' 的商品。");
        } else {
            System.out.println("找到 " + results.size() + " 个包含标签 '" + tag + "' 的商品:");
            System.out.println("-".repeat(80));
            for (Product3 product : results) {
                System.out.println(product);
            }
            System.out.println("-".repeat(80));
        }
    }

    private void viewAllTags() {
        System.out.println("\n--- 所有商品标签 ---");
        Set<String> allTags = productService.getAllTags();
        if (allTags.isEmpty()) {
            System.out.println("当前没有可用的标签。");
        } else {
            System.out.println("标签总数: " + allTags.size());
            System.out.println("所有标签: " + allTags);

            // 显示每个标签的商品数量
            System.out.println("\n各标签商品统计:");
            System.out.println("-".repeat(40));
            for (String tag : allTags) {
                List<Product3> productsWithTag = productService.findProductsByTag(tag);
                System.out.printf("%-8s: %d 个商品\n", tag, productsWithTag.size());
            }
        }
    }

    private void displayTagStatistics() {
        Set<String> allTags = productService.getAllTags();
        if (!allTags.isEmpty()) {
            System.out.println("\n📊 标签统计:");
            int productsWithTags = 0;
            for (Product3 product : productService.getAllProducts()) {
                if (product.getTagCount() > 0) {
                    productsWithTags++;
                }
            }
            System.out.printf("有标签的商品: %d/%d\n", productsWithTags, productService.getAllProducts().size());
            System.out.println("所有标签: " + allTags);
        }
    }

    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product3 product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.println("商品信息: " + product);
        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        int currentQuantity = shoppingCart.getOrDefault(productId, 0);
        shoppingCart.put(productId, currentQuantity + quantity);
        System.out.println("✅ 成功将 '" + product.getName() + "' " + quantity + "件添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("🛒 购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int totalItems = 0;

        System.out.println("-".repeat(70));
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product3 product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                totalItems += quantity;
            }
        }
        System.out.println("-".repeat(70));
        System.out.printf("商品总数: %d 件 | 总计: ¥%.2f\n", totalItems, total);
    }

    private int getIntInput(String prompt) {
        while (true) {
            System.out.print(prompt);
            if (scanner.hasNextInt()) {
                return scanner.nextInt();
            } else {
                System.out.println("请输入有效的数字！");
                scanner.next(); // 清除无效输入
            }
        }
    }

    public static void main(String[] args) {
        new ConsoleShop3().start();
    }
}